package org.jash.utils

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder

class CommonAdapter<D>(val layout:(D)->Pair<Int, Int>, val data:MutableList<D> = mutableListOf(), val spanSize:(D) -> Int = { 1 }):Adapter<CommonViewHolder>() {
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        (recyclerView.layoutManager as? GridLayoutManager)?.spanSizeLookup = object :SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int = spanSize(data[position])
        }
    }

    override fun getItemViewType(position: Int): Int = layout(data[position]).first

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommonViewHolder =
        CommonViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), viewType, parent, false))

    override fun getItemCount(): Int = data.size

    override fun onBindViewHolder(holder: CommonViewHolder, position: Int) {
        holder.binding.setVariable(layout(data[position]).second, data[position])
    }
    fun add(d:D, position: Int = -1) {
        var s = position
        if (position >= 0) {
            data.add(s, d)
        } else {
            data.add(d)
            s = data.size
        }
        notifyItemInserted(s)
    }
    operator fun plusAssign(d:Collection<D>) {
        val size = data.size
        data += d
        notifyItemRangeInserted(size, d.size)
    }
}
class CommonViewHolder(val binding: ViewDataBinding
): ViewHolder(binding.root)